package org.kanstantin.nwscan.crawler;

import java.io.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.List;

/**
 * @author kanstantin
 *
 */
public class FileResultProcessor implements ResultsWritable {
	private File outputDir;
	private final static String FS = "|";
	private PrintWriter output;
	private DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");

	public void setOutputDir(File outputDir) {
		this.outputDir = outputDir;
	}

	@Override
	public boolean save(SearchResult r) {
		if (output == null) {
			openOutput();
		}

		output.printf("%s|%s|%s|%s|%s|%s|%s\n", r.getHost(), r.getShare(), r.getPath(), r.getFilename(),
											   r.getExtension(), r.getSize(), dateFormat.format(r.getCreated()));

		return true;
	}

	@Override
	public boolean save(List<SearchResult> results) {
		for (SearchResult searchResult: results) {
			save(searchResult);
		}
		return true;
	}

    @Override
    public void close() {
        //To change body of implemented methods use File | Settings | File Templates.
    }

    private void openOutput() {
		File f = new File(outputDir.getAbsolutePath() + File.separatorChar + generateFilename());
		OutputStream fs = null;
		try {
			f.createNewFile();
			fs = new FileOutputStream(f);
		} catch (IOException ioex) {
			throw new RuntimeException(ioex);
		}

		output = new PrintWriter(fs);
	}

	private String generateFilename() {
		return System.currentTimeMillis() + ".csv";
	}
}
